package com.sbl.bajw.common.web;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class WebContext {
	
	private static ThreadLocal<HttpServletRequest> ThreadRequest =new ThreadLocal<HttpServletRequest>();
	
	private static ThreadLocal<HttpServletResponse> ThreadResponse =new ThreadLocal<HttpServletResponse>();
	
	private static ThreadLocal<List<FileItem>> ThreadFileItems =new ThreadLocal<List<FileItem>>();
	
	public static void setRequest(HttpServletRequest httpServletRequest)
	{
		ThreadRequest.set(httpServletRequest);
		List<FileItem> items;
		try {
			DiskFileItemFactory f = new DiskFileItemFactory(10485760,new File("D:/tem/"));
			ServletFileUpload upload=new ServletFileUpload(f); 
			
			upload.setHeaderEncoding("utf-8");  
			items =upload.parseRequest(httpServletRequest);
			ThreadFileItems.set(items);
		} catch (FileUploadException e) {
		}
		
	}
	
	public static HttpServletRequest getRequest()
	{
		ServletRequestAttributes requestAttr = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttr.getRequest();
		return request;
	}
	
	public static List<FileItem> getFileItems()
	{
		List<FileItem> items = null;
		try {
			items = ThreadFileItems.get();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return items;
	}
	
	public static void setResponse(HttpServletResponse httpServletResponse)
	{
		httpServletResponse.setContentType("text/html;charset=UTF-8");
		ThreadResponse.set(httpServletResponse);
	}
	
	public static HttpServletResponse getResponse()
	{
		HttpServletResponse response = ThreadResponse.get();
		return response;
	}

}